package  ucas.pin.web.services;

import java.text.Collator;
import java.util.*;

import ucas.pin.web.domain.Prescription;
import ucas.pin.web.domain.Consist;
import ucas.pin.web.domain.Disease;
import ucas.pin.web.domain.Entity;
import ucas.pin.web.domain.MedMaterial;
import ucas.pin.web.domain.Treat;
import ucas.pin.web.dto.GraphDto;
import ucas.pin.web.dto.LinkDto;
import ucas.pin.web.dto.NodeDto;
import ucas.pin.web.repositories.DiseaseRepository;
import ucas.pin.web.repositories.PrescriptionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PrescriptionService {

	@Autowired PrescriptionRepository prescriptionRepository;

	
	
	//center is Prescription
	private GraphDto toEchartsFormat(Collection<Prescription> coll_pre){	
		List<NodeDto> listNode = new ArrayList();
		List<LinkDto> listLink = new ArrayList();
		for(Prescription pre : coll_pre) {
			listNode.add(pre.toNodeDto(0));
			System.out.println(pre.getName()+":"+pre.getId());
			for(Consist con : pre.getConsists()) {
				MedMaterial med = (MedMaterial)con.getEnd_Entity();
				System.out.println(med.getName());
				System.out.println(med.getId());
				listNode.add(med.toNodeDto());
				listLink.add(con.toLinkDto());
			}
			for(Treat tre : pre.getTreates()){
				Disease des = (Disease)tre.getEnd_Entity();
				listNode.add(des.toNodeDto(2));
				listLink.add(tre.toLinkDto());
				//System.out.println(des.getName()+":"+des.getId());
			}
		}
		
		return new GraphDto(listNode,listLink);
	}
	public GraphDto graph(String name) {
		Collection<Prescription> result = prescriptionRepository.getGraphByName(name);
		if(result.isEmpty()) {
			result = prescriptionRepository.getGraphConsistByName(name);
		}
		if(result.isEmpty()) {
			result = prescriptionRepository.getGraphTreatByName(name);
		}
		if(result.isEmpty()) {
			result = prescriptionRepository.getEntityByName(name);
		}
		//test_Pre(result);
		System.out.println("get Graph ............"+name);
		return toEchartsFormat(result);
	}
	public Collection<Prescription> searchByKeyWord(String name) {
		Collection<Prescription> result = prescriptionRepository.findPrescriptionByNameLike(".*"+name+".*");
		//test_Pre(result);
		//System.out.println("get Graph ............"+name);
		return result;
	}
	

}
